<?php

class Welcome_model extends CI_Model {

    function login_validation($data) {
        $sql = "SELECT * FROM users where username='" . $data['username'] . "' AND password='" . do_hash($data['password'], 'md5') . "';";
        $query = $this->db->query($sql);
        $row = $query->row();
        //var_dump($data);
        if ($data['username'] == $row->username && do_hash($data['password'], 'md5') == $row->password) {
            $row->logged_in = true;
            $userdata = (array) $row;

            $this->session->set_userdata($userdata);
            return true;
        }
        return false;
    }

    function register_user($data) {

        $insert_user = false;
        $insert_profile = false;

        $usersdata = array(
            'username' => $data['email'],
            'password' => do_hash($data['password'], 'md5'),
            'email' => $data['email'],
            'is_loggin' => 0
        );


        if ($this->db->insert('users', $usersdata)) {
            $insert_user = true;
        }

        $userid = $this->db->insert_id();

        if ($insert_user) {
            $profile_data = array(
                'user_id' => $userid,
                'firstname' => $data['firstname'],
                'lastname' => $data['lastname'],
                'sex' => $data['sex'],
            );

            if ($this->db->insert('users_profile', $profile_data)) {
                $insert_profile = true;
            }
        }

        if ($insert_user && $insert_profile) {
            $usersdata['logged_in'] = 1;
            $this->session->set_userdata($usersdata);
            if ($this->users_lib->is_login()) {
                $this->db->where('user_id', $userid);
                $this->db->set('is_loggin', 1);
                $this->db->update('users');
            }
        }
        return $this->users_lib->is_login() && $insert_profile && $insert_user;
    }

    function check_unique_mail($mail) {

        $result = $this->db->query("SELECT email FROM users WHERE email='$mail';")->row();

        if (empty($result)) {
            return TRUE;
        }
        RETURN FALSE;
    }

}